﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input.EliminationmodelsInput;
using IntelligentAgriculture.Contracts.Dto.Output.EarTagOutput;
using IntelligentAgriculture.Contracts.Dto.Output.EliminationmodelsOutput;
using IntelligentAgriculture.Contracts.Dto.Output.PageOutput;
using IntelligentAgriculture.Contracts.Interface.EliminationModelService;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.EliminationModel;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace IntelligentAgriculture.Services.EliminationModelServices
{

    public class EliminationsModelService : IEliminationModelService
    {
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IridegRepository _iridegRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IColumnManRepository _columnManRepository;

        /// <summary>
        /// 耳号仓储
        /// </summary>
        private readonly IEarTagReposiotry _earTagReposiotry;
        /// <summary>
        /// 羊只档案仓储
        /// </summary>
        private readonly ISheepAblactationRepository _sheepFileModelRepository;

        private readonly ISheepFileModelRepository _ISheepFileModelRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SheepAblactationService> _logger;
        private readonly IEliminationModelRepository _IEliminationModelRepository;

    
       
        public EliminationsModelService(IMapper mapper, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IEarTagReposiotry earTagReposiotry, ISheepAblactationRepository sheepFileModelRepository, ISheepFileModelRepository iSheepFileModelRepository, ILogger<SheepAblactationService> logger, IEliminationModelRepository iEliminationModelRepository)
        {
            _mapper = mapper;
            _iridegRepository = iridegRepository;
            _columnManRepository = columnManRepository;
            _earTagReposiotry = earTagReposiotry;
            _sheepFileModelRepository = sheepFileModelRepository;
            _ISheepFileModelRepository = iSheepFileModelRepository;
            _logger = logger;
            _IEliminationModelRepository = iEliminationModelRepository;
        }
        /// <summary>
        /// 批量添加淘汰信息
        /// </summary>
        /// <param name="entitys">要添加淘汰信息列表</param>
        /// <returns>添加操作影响的行数。</returns>
        public async Task<int> Add(List<Eliminationmodel> entitys)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                  
                    int result = await _IEliminationModelRepository.Add(entitys);

                   
                    var list = await _ISheepFileModelRepository.GetSheepfilemodels();
                    var sheepFileModels = new List<Sheepfilemodel>();
                    foreach (var entity in entitys)
                    {
                        var sheepFileModel = list.FirstOrDefault(x => x.EarTag == entity.EarTag);
                        if (sheepFileModel != null)
                        {
                            sheepFileModel.PresentState = 5;
                        }
                        sheepFileModels.Add(sheepFileModel);
                    }

                    await _ISheepFileModelRepository.UpdateListSheepFileModel(sheepFileModels); 

                    // 提交事务
                    transaction.Complete();

                    return result; 
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    Console.WriteLine("事务回滚: " + ex.Message);
                    throw; // 抛出异常或返回错误状态码，让调用者处理
                }
            }
        }



        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> Delete(int id)
        {
            try
            {
                return await _IEliminationModelRepository.Delete(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteRange(IEnumerable<int> ids)
        {
            try
            {
                return await _IEliminationModelRepository.DeleteRange(ids);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 反填功能
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Eliminationmodel> Find(int id)
        {
            try
            {
                var list = await _IEliminationModelRepository.Find(id);
                if (list == null)
                {
                    return null;
                }
                var lists = _mapper.Map<Eliminationmodel>(list);
                return lists;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示，查询，分页功能
        /// </summary>
        /// <param name="input">查询的参数</param>
        /// <returns>返回列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagesOutput<EliminationmodelShowOutput>> GetShow(EliminationmodelShowInput input)
        {
            try
            {
                var list = await _IEliminationModelRepository.GetShow();
                if (!string.IsNullOrEmpty(input.EarTag))
                {
                    list = list.Where(x => x.EarTag.Contains(input.EarTag));
                }
                if (input.DepartureState > 0)
                {
                    list = list.Where(x => x.DepartureState == input.DepartureState);
                }
                if (input.Siwang > 0)
                {
                    list = list.Where(x => x.Siwang == input.Siwang);
                }


                var result = new PagesOutput<EliminationmodelShowOutput>()
                {
                    Total = list.Count(),
                    PageSize = input.PageSize
                };

                var query = list.OrderByDescending(x => x.EliminationId).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize);
                result.Data = _mapper.Map<List<EliminationmodelShowOutput>>(query);
                return result;
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpateEartag(Eliminationmodel entity)
        {
            try
            {
                var list = _mapper.Map<Eliminationmodel>(entity);
                return await _IEliminationModelRepository.UpdateAsync(list);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
